import React, {PureComponent} from "react";
import {
    Platform,
    StyleSheet,
    Text,
    View,
    Button,
    SafeAreaView,
    ScrollView,
    Image,
    Dimensions,
    TouchableOpacity,
    FlatList
} from "react-native";
import color from "../../../widget/color";
import {ImageButton} from '../../../widget/CustomButton'
import RefreshListView, {RefreshState} from "react-native-refresh-list-view";
import MineAddressListCell from '../../../widget/mine/MineAddressListCell'
import AddAddressScene from "./AddAddressScene";
import api from '../../../api/api'
import method from '../../../api/method'
import {fetchGetRequest, fetchPostRequest} from '../../../api/NetworkTool'
import NetTool from '../../../api/NetTool'
// import Toast, {DURATION} from 'react-native-easy-toast'
import Tips from 'react-native-root-tips'
import EmptyCouponView from "../../../widget/CommonEmptyView";
import CommonAlertDialog from '../../../widget/dialog/CommonAlertDialog'

const {width} = Dimensions.get('window')
const {height} = Dimensions.get('window')
type Props = {
    navigation:any,
}

type State = {
    data: Array<Object>,
    refreshState: number,
}

export default class MineAddressScene extends PureComponent<Props,State> {

    static navigationOptions = ({navigation}: any) => ({
        headerTintColor: 'white',
        title: '我的地址',
        headerStyle: {
            backgroundColor: color.primary,
            borderBottomColor:color.primary,
        },
        headerRight: <Text/>,
        headerLeft:<TouchableOpacity onPress={()=>{
            navigation.state.params.callback('回调参数');
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../../res/img/video/back.png')}/>
        </TouchableOpacity>
    });

    constructor(props) {
        super(props)
        this.state = {
            data: [],
            refreshState: RefreshState.Idle,
            show_alert:false,
            addrId:'',
        }
    }

    requestData = async() => {

        let json = await NetTool.fetchGetRequest(api.getUserAddr, method.get)


        let dataList = json.addrList.map((info) => {
            return {
                id: info.id,
                city_id: info.city_id,
                city_name: info.city_name,
                address: info.address,
                isDefault: info.isDefault,
                mobile: info.mobile,
                receiver: info.receiver,
                remark: info.remark,
                user_id: info.user_id,
            }
        })


        return dataList
    }


    requestFirstPage = async() => {

        try {
            this.setState({refreshState: RefreshState.HeaderRefreshing})
            let dataList = await this.requestData()

            this.setState({
                data: dataList,
                refreshState: RefreshState.Idle,
            })
        } catch (error) {
            this.setState({
                refreshState: RefreshState.Failure,
            })
        }
    }
    requestNextPage = async() => {
    }

    deleteUserAddr(addrId) {

        this.setState({show_alert:true, addrId:addrId})


    }

    confirmOpress(){
        let params = {
            addrId: this.state.addrId,
        }

        fetchPostRequest(api.removeUserAddr, method.post, params)
            .then(res => {
                this.requestFirstPage()
            }).catch(err => {
            console.log(err)
        })
    }

    editUserAddr(item) {
        this.props.navigation.navigate('EditAddressScene', {
            info: item, callback: (data) => {
                this.requestFirstPage()
            }
        })
    }

    updateIsDefault(addrId) {
        let params = {
            addrId: addrId,
        }
        fetchPostRequest(api.updateDefaultAddr, method.post, params)
            .then(res => {
                Tips.showSuccess('设置成功', {mask: true})
                this.requestFirstPage()
            })
            .catch(err => {

            })
    }

    componentDidMount() {
        this.requestFirstPage()
    }

//custon ui
    keyExtractor = (item: Object, index: number) => {
        return index + ''
    }
    renderCell = (rowData: any) => {

        const {isOrder} = this.props.navigation.state.params
        return (
            <MineAddressListCell onPress={()=>{
                if (isOrder){
                    let params = {
                        addrId:rowData.item.id,
                    }
                    fetchPostRequest(api.updateDefaultAddr,method.post,params)
                        .then(res=>{
                            const {navigation} = this.props
                            navigation.state.params.callback('回调参数');
                            navigation.goBack()
                        })
                        .catch(err=>{

                        })
                }
            }} navigation={this.props.navigation} info={rowData.item} defaultPress={()=>{
                this.updateIsDefault(rowData.item.id)
            }} deletePress={()=>{this.deleteUserAddr(rowData.item.id)}} editPress={()=>{
                this.editUserAddr(rowData.item)
            }}/>
        )
    }

    render() {
        return (

            <SafeAreaView style={styles.container}>

                <RefreshListView
                    ListHeaderComponent={() => (
                    !this.state.data.length?
                    <EmptyCouponView height={(height-200)} tip={'没有收货地址了哟'} source={require('../../../../res/img/address/dizhi.png')}/>
                     : null)
                    }
                    data={this.state.data}
                    renderItem={this.renderCell}
                    keyExtractor={this.keyExtractor}
                    refreshState={this.state.refreshState}
                    onHeaderRefresh={this.requestFirstPage}
                    onFooterRefresh={this.requestNextPage}
                    ItemSeparatorComponent={()=><View style={{width:width,height:6,backgroundColor:'#F9F9F9'}}/>}
                />
                <CommonAlertDialog title={'确定删除地址？'} onPress={()=>{
                    this.confirmOpress()
                }} closeModal={(statu)=>{this.setState({show_alert:statu})}} confirmTitle={'确定'} show={this.state.show_alert}/>
                <TouchableOpacity onPress={()=>{this.props.navigation.navigate('AddAddressScene',{callback:(data)=>{
                    this.requestFirstPage()
                }})}}
                                  style={{height:50,backgroundColor:color.globalMainColor,alignItems:'center',justifyContent:"center"}}>
                    <Text style={{fontSize:16,fontWeight:'bold',color:'white'}}>添加新的收货地址</Text>
                </TouchableOpacity>
            </SafeAreaView>

        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
        width: width,
    },
});




